from reportlab.platypus import Paragraph, Table, Flowable, XPreformatted, Spacer
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.enums import TA_LEFT, TA_RIGHT, TA_CENTER, TA_JUSTIFY
from reportlab.lib.units import inch
from reportlab.lib import colors

from settings import *
from title24_styles import t24_styles


def get_draw_width():
    return PAGE_WIDTH - LEFT_MARGIN - RIGHT_MARGIN


def get_draw_height():
    return PAGE_HEIGHT - TOP_MARGIN - BOTTOM_MARGIN \
           - HEADER_HEIGHT - FOOTER_HEIGHT


def get_remaining_width(widths):
    """Returns a list including the widths and the draw width minus the sum of
    the widths, whatever space is remaining, or zero, whichever is greater.
    """
    used = sum(widths)
    remaining = get_draw_width() - used
    if remaining < 0.0: remaining = 0.0
    return_list = list(widths)
    return_list.append(remaining)
    return return_list


def eighth_inch_spacer():
    return Spacer(get_draw_width(), 0.125*inch)


def sixteenth_inch_spacer():
    return Spacer(get_draw_width(), 0.0625*inch)


def get_indent_pp_style(first_line_indent=0, space_before=3):
    return ParagraphStyle(
        name='custom_style',
        parent=t24_styles()['cec_body'],
        firstLineIndent=first_line_indent,
        spaceBefore=space_before,
    )


def bullet(text, first_line_indent=0, space_before=3):
    return Paragraph(
        "%s" % text,
        get_indent_pp_style(),
        bulletText='O'
    )


def bullets(*args, **kwargs):
    first_line_indent = kwargs.get('first_line_indent', 0)
    space_before = kwargs.get('space_before', 3)
    return [
        bullet(
            str,
            first_line_indent=first_line_indent,
            space_before=space_before
        )
        for str in args
    ]


def sequence(text, seq_id=None):
    from datetime import datetime
    if not seq_id:
        sid = datetime.now().strftime("%s")
    return Paragraph(
        '<seq id="%s"/>. %s' % (seq_id, text),
        get_indent_pp_style(),
    )


def sequences(*args, **kwargs):
    from datetime import datetime
    sid = kwargs.get('seq_id', None)
    if not sid:
        sid = datetime.now().strftime("%s")
    return [sequence(str, sid) for str in args]


def label_pp(text):
    return Paragraph(text, t24_styles()['label'])


def mc_label_pp(text):
    return Paragraph(text, t24_styles()['mc_label'])


def mc_table_pp(text):
    table_style = ParagraphStyle(
        parent=t24_styles()['label'],
        name='t',
        alignment=TA_CENTER,
    )
    return Paragraph(text, table_style)


def notes_pp(text):
    return Paragraph(text, t24_styles()['notes'])


def body_pp(text):
    return Paragraph("%s" % text, t24_styles()['cec_body'])


def body_pp_list(list_of_strings):
    return [body_pp(str) for str in list_of_strings]


def col_hdr(text):
    return Paragraph("%s" % text, t24_styles()['cec_col_hdr'])


def col_hdr_list(list_of_strings):
    return [col_hdr(str) for str in list_of_strings]


def col_hdrs(*args):
    return [col_hdr(str) for str in args]


def h2_pp(text):
    return Paragraph("%s" % text, t24_styles()['cec_h2'])


def h2_bold_pp(text):
    return Paragraph("<b>%s</b>" % text, t24_styles()['mc_h2'])


def h3_pp(text):
    return Paragraph("%s" % text, t24_styles()['cec_h3'])


def h3_bold_pp(text):
    return Paragraph("<b>%s</b>" % text, t24_styles()['cec_h3'])


def section_char():
    return '&#167;'


def add_sxn_chr(text, prefix=''):
        return "%s%s%s" % (prefix, section_char(), text)


def tag_medium(text, **kwargs):
    return XPreformatted(
        "<para><b>%s</b></para>" % text,
        t24_styles(**kwargs)['tag_medium'],
    )


def tag_medium_center(text, **kwargs):
    return Paragraph(
        "<para><b>%s</b></para>" % text,
        t24_styles(**kwargs)['tag_medium_center'],
    )


def tag_small_center(text, **kwargs):
    return Paragraph(
        "<para>%s</para>" % text,
        t24_styles(**kwargs)['tag_small_center'],
    )


class TitleBlock(Table):
    """"""
    def __init__(self, title, page_x_of_y, short_name):
        styles = t24_styles()
        if page_x_of_y != "":
            col1 = 1.25*inch
        else:
            col1 = 0
        col2 = 1.0*inch
        col0 = get_draw_width()-col1-col2
        b = "<b>%s</b>"
        Table.__init__(self,
            data=(
                (Paragraph(b % title, styles['title']),
                 Paragraph(page_x_of_y, styles['title']),
                 Paragraph(b % short_name, styles['title_right']),
                ),
            ),
            colWidths=(col0, col1, col2),
            rowHeights=(HEADER_HEIGHT,),
            style=[
                ('BOX',(0,0),(-1,-1),LINE_WIDTH,colors.black),
                ('VALIGN',(0,0),(0,0),'MIDDLE'),
                ('ALIGN',(0,0),(0,0),'LEFT'),
                ('ALIGN',(1,0),(1,0),'CENTER'),
                ('ALIGN',(2,0),(2,0),'RIGHT'),
            ],
        )


class FooterBlock(Table):
    """"""
    def __init__(self, **kwargs):
        styles = t24_styles(**kwargs)
        col_width = get_draw_width() / 3.0
        Table.__init__(
            self,
            data=(
                (
                    Paragraph(
                        '<para align="left">%s</para>' % \
                        kwargs.get('footer_left_text', ''),
                        styles['footer']
                    ),
                    Paragraph(
                       '<para align="center">%s</para>' % \
                       kwargs.get('footer_center_text', ''),
                       styles['footer']
                   ),
                    Paragraph(
                       '<para align="right">%s</para>' % \
                       kwargs.get('footer_right_text', ''),
                       styles['footer']
                   ),
                ),
            ),
            colWidths=(col_width, col_width, col_width),
            rowHeights=(FOOTER_HEIGHT,),
            style=[
                ('BOX',(0,0),(-1,-1),LINE_WIDTH,colors.black),
                ('ALIGN',(0,0),(0,0),'LEFT'),
                ('ALIGN',(1,0),(1,0),'CENTER'),
                ('ALIGN',(2,0),(2,0),'RIGHT'),
            ],
    )


def draw_footer(canvas, **kwargs):
    """Draws the footer on the canvas"""
    t = FooterBlock(**kwargs)
    t.wrap(PAGE_WIDTH, PAGE_HEIGHT)
    t.drawOn(canvas, LEFT_MARGIN, BOTTOM_MARGIN)


class CoverPage(Table):
    def __init__(self, **kwargs):
        styles = t24_styles(**kwargs)
        block0 = Table(
            data=(( Paragraph(TITLE_XML, styles['title']), ),),
            colWidths=(get_draw_width(),),
            rowHeights=(HEADER_HEIGHT,),
            style=[
                ('BOX',(0,0),(-1,-1),LINE_WIDTH,colors.black),
                ('ALIGN',(0,0),(-1,-1),'CENTER'),
            ],
        )
        # Project info
        block1 = XPreformatted(
            """<para spacebefore="0" spaceafter="64" align="center">




<b>TITLE 24 REPORT FOR:</b>
%(project_title)s
%(project_addr_formatted)s


</para>""" % dict(
                project_title=kwargs.get(
                    'project_title',
                    'MISSING PROJECT_TITLE'
                ),
                project_addr_formatted=kwargs.get(
                    'project_addr_formatted',
                    'MISSING PROJECT_ADDR_FORMATTED'
                ),
            ),
            styles['title'],
        )
        # Designer info
        block2 = XPreformatted(
            """<para spacebefore="64" spaceafter="64" align="center">


<b>PREPARED FOR:</b>
%(designer_company_name)s
%(designer_name)s
%(designer_addr_formatted)s


</para>""" % dict(
                designer_company_name=kwargs.get(
                    'designer_company_name',
                    'MISSING DESIGNER_COMPANY_NAME'
                ),
                designer_name=kwargs.get(
                    'designer_name',
                    'MISSING DESIGNER_NAME'
                ),
                designer_addr_formatted=kwargs.get(
                    'designer_addr_formatted',
                    'MISSING DESIGNER_ADDR_FORMATTED'
                ),
            ),
            styles['title'],
        )
        # DocAuthor info
        block3 = XPreformatted(
            """<para spacebefore="64" spaceafter="1200" align="center">


<b>PREPARED BY:</b>
%(doc_author_company_name)s
%(doc_author_name)s
%(doc_author_addr_formatted)s


</para>""" % dict(
                doc_author_company_name=kwargs.get(
                    'doc_author_company_name',
                    'MISSING DOC_AUTHOR_COMPANY_NAME'
                ),
                doc_author_name=kwargs.get(
                    'doc_author_name',
                    'MISSING DOC_AUTHOR_NAME'
                ),
                doc_author_addr_formatted=kwargs.get(
                    'doc_author_addr_formatted',
                    'MISSING DOC_AUTHOR_ADDR_FORMATTED'
                ),
            ),
            styles['title'],
        )
        # A 1x4 table
        Table.__init__(self,
            data=(
                (block0,),
                (block1,),
                (block2,),
                (block3,),
                ),
            colWidths=(get_draw_width(),),
            style=[
                ('ALIGN',(0,0),(-1,-1),'CENTER'),
            ],
        )

